package controller

import (
	"GoAdmin/common"
	"GoAdmin/models"
	"GoAdmin/service"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func GetMenuNew(c *gin.Context) {
	var (
		user *models.OaUser
		ok   bool
	)
	if user, ok = common.GetCtxUser(c); !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "用户信息验证失败"})
		return
	}
	log.Println(user)
	list, err := new(models.OaMenu).GetMenuList()
	if err != nil {
		log.Println(err)
	}
	var fm []map[string]interface{}
	for _, v := range list {
		if v.ParentId == 0 {
			menu := map[string]interface{}{}
			menu["title"] = v.Title
			menu["id"] = v.Id
			fm = append(fm, menu)
		}
	}
	for _, f := range fm {
		var sm []map[string]interface{}
		for _, v := range list {
			if v.ParentId == f["id"] {
				smenu := map[string]interface{}{}
				smenu["title"] = v.Title
				sm = append(sm, smenu)
			}
		}
		f["sub"] = sm
		delete(f, "id")
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "ok", "data": fm})
	// return
}

// GetMenuList 通过用户获取对应Role的菜单树, 只有两种Role
func GetMenuList(c *gin.Context) {
	var userId string
	if c.Request.Method == "GET" {
		userId = c.Query("user_id")
	} else {
		userId = c.PostForm("user_id")
	}

	role, _ := new(models.OaUser).GetByUser(userId)

	// TODO: 区分账号角色
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "ok", "data": models.GetAdminMenu(role.Type, role.Id)})
	return
}

func GetAuth(c *gin.Context) {
	list := service.Enforcer.GetFilteredNamedPolicy("p", 0, "admin")
	namedGroupingPolicy := service.Enforcer.GetFilteredNamedGroupingPolicy("g", 0, "yu")
	log.Print(list, namedGroupingPolicy)
	for _, vlist := range list {
		log.Println(vlist[1], vlist[3])
		//for _, v := range vlist {
		//	log.Println(v)
		//	//fmt.Printf("value: %s, ", v)
		//}
	}
}
